package com.googlecode.grima.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.googlecode.grima.base.Page;
import com.googlecode.grima.base.SearchResult;
import com.googlecode.grima.domain.Partner;
import com.googlecode.grima.service.PartnerService;

@Controller
public class PartnerController extends PortalController {

	private static final long serialVersionUID = 1L;
	
	@Autowired
	private PartnerService partnerService;

	public PartnerService getPartnerService() {
  	return partnerService;
  }

	public void setPartnerService(PartnerService partnerService) {
  	this.partnerService = partnerService;
  }

	@RequestMapping(value = "/secure/partners", method = RequestMethod.GET)
	public String partners(HttpServletRequest request, ModelMap modelMap) {
		Page page = new Page(request);
		
		SearchResult<Partner, Long> partners = null;

		String name = request.getParameter("name");
		
		if ( StringUtils.isNotEmpty(name)) {
			partners = partnerService.findByParameters(name, null, page);	
		} else {
			partners = partnerService.findAll(page);	
		}
		
		modelMap.addAttribute("name", name);
		modelMap.addAttribute("count", partners.getTotal());
		modelMap.addAttribute("partners", partners.getRows());
		modelMap.addAttribute("page", page);
		
		return "/secure/partners";

	}
	
  @RequestMapping(value="/secure/partnerZoom", method = {RequestMethod.GET, RequestMethod.POST})
  public @ResponseBody String partnerZoom(HttpServletRequest request, Partner partner, BindingResult bindingResult, ModelMap modelMap) {    
  	
		SearchResult<Partner, Long> partners = null;

		String name = partner.getName();
		
		if ( StringUtils.isNotEmpty(name)) {
			partners = partnerService.findByParameters(name, null, null);	
		} else {
			partners = partnerService.findAll(null);	
		}
  	
		String json = new Gson().toJson(partners);
		
    return json;
  }

}